<template>
  <div class="customer-visit">
    <el-page-header @back="goBack" title="客户回访">
      <template #content>
        <span class="page-header-content">{{ customerInfo.name }}</span>
      </template>
    </el-page-header>

    <div class="visit-content">
      <!-- 客户基本信息卡片 -->
      <el-card class="info-card">
        <template #header>
          <div class="card-header">
            <h3>客户信息</h3>
          </div>
        </template>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="客户姓名">{{ customerInfo.name }}</el-descriptions-item>
          <el-descriptions-item label="客户类型">
            {{ customerInfo.type === 'personal' ? '个人' : '企业' }}
          </el-descriptions-item>
          <el-descriptions-item label="手机号码">{{ customerInfo.phone }}</el-descriptions-item>
          <el-descriptions-item label="信用等级">
            <el-tag :type="getCreditRatingType(customerInfo.creditRating)">
              {{ getCreditRatingText(customerInfo.creditRating) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="最近回访时间">{{ customerInfo.lastVisitTime }}</el-descriptions-item>
          <el-descriptions-item label="下次回访时间">{{ customerInfo.nextVisitTime }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 回访记录时间线 -->
      <el-card class="timeline-card">
        <template #header>
          <div class="card-header">
            <h3>回访记录</h3>
            <el-button type="primary" @click="handleAdd">新增回访</el-button>
          </div>
        </template>

        <div v-loading="loading">
          <el-timeline>
            <el-timeline-item
              v-for="(visit, index) in visitRecords"
              :key="index"
              :timestamp="visit.visitTime"
              :type="getVisitType(visit.method)"
            >
              <el-card class="visit-card">
                <template #header>
                  <div class="visit-header">
                    <div class="visit-info">
                      <el-tag :type="getVisitType(visit.method)" class="visit-method">
                        {{ getVisitMethodText(visit.method) }}
                      </el-tag>
                      <span class="visit-visitor">回访人：{{ visit.visitor }}</span>
                    </div>
                    <div class="visit-actions" v-if="canEdit(visit)">
                      <el-button 
                        type="primary" 
                        link
                        @click="handleEdit(visit)"
                      >
                        编辑
                      </el-button>
                      <el-button 
                        type="danger" 
                        link
                        @click="handleDelete(visit)"
                      >
                        删除
                      </el-button>
                    </div>
                  </div>
                </template>
                <div class="visit-content">
                  <p class="visit-text">{{ visit.content }}</p>
                  <div class="visit-footer">
                    <el-rate 
                      v-model="visit.feedback"
                      disabled
                      show-score
                      text-color="#ff9900"
                    />
                    <span class="next-visit-time">下次回访：{{ visit.nextVisitTime }}</span>
                  </div>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>

          <div class="empty-text" v-if="visitRecords.length === 0">
            暂无回访记录
          </div>

          <div class="pagination" v-if="visitRecords.length > 0">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </el-card>
    </div>

    <!-- 回访记录对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogType === 'add' ? '新增回访记录' : '编辑回访记录'"
      width="500px"
    >
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="formRef"
        label-width="100px"
      >
        <el-form-item label="回访方式" prop="method">
          <el-select v-model="form.method" placeholder="请选择回访方式" style="width: 100%">
            <el-option label="电话" value="phone" />
            <el-option label="上门" value="visit" />
            <el-option label="邮件" value="email" />
            <el-option label="短信" value="sms" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="回访内容" prop="content">
          <el-input
            type="textarea"
            v-model="form.content"
            :rows="3"
            placeholder="请输入回访内容"
          />
        </el-form-item>
        <el-form-item label="客户反馈" prop="feedback">
          <el-rate 
            v-model="form.feedback"
            :texts="['很差', '较差', '一般', '满意', '很满意']"
            show-text
          />
        </el-form-item>
        <el-form-item label="跟进事项" prop="followUp">
          <el-input
            type="textarea"
            v-model="form.followUp"
            :rows="2"
            placeholder="请输入需要跟进的事项"
          />
        </el-form-item>
        <el-form-item label="下次回访" prop="nextVisitTime">
          <el-date-picker
            v-model="form.nextVisitTime"
            type="datetime"
            placeholder="请选择下次回访时间"
            style="width: 100%"
            :disabled-date="disabledDate"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { customerApi } from '@/api/customer'

export default {
  name: 'CustomerVisit',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const loading = ref(false)
    
    // 客户信息
    const customerInfo = ref({})
    const custId = ref(parseInt(route.params.id) || 0)
    
    // 回访记录
    const visitRecords = ref([])
    
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)

    // 对话框相关
    const dialogVisible = ref(false)
    const dialogType = ref('add')
    const formRef = ref(null)
    const form = reactive({
      custId: 0,
      visitTime: '',
      method: '',
      visitor: '',
      content: '',
      feedback: 3,
      nextVisitTime: ''
    })

    const rules = {
      method: [
        { required: true, message: '请选择回访方式', trigger: 'change' }
      ],
      content: [
        { required: true, message: '请输入回访内容', trigger: 'blur' },
        { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
      ],
      feedback: [
        { required: true, message: '请选择客户反馈', trigger: 'change' }
      ],
      followUp: [
        { required: true, message: '请输入跟进事项', trigger: 'blur' },
        { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' }
      ],
      nextVisitTime: [
        { required: true, message: '请选择下次回访时间', trigger: 'change' }
      ]
    }

    // 方法定义
    const goBack = () => {
      router.back()
    }

    const handleSearch = () => {
      loading.value = true
      // TODO: 实现查询逻辑
      setTimeout(() => {
        loading.value = false
      }, 1000)
    }

    const handleAdd = () => {
      dialogType.value = 'add'
      Object.keys(form).forEach(key => {
        form[key] = key === 'feedback' ? 3 : ''
      })
      form.custId = custId.value
      form.visitTime = new Date().toISOString().substr(0, 19).replace('T', ' ')
      form.visitor = JSON.parse(localStorage.getItem('userInfo') || '{}').userName || ''
      dialogVisible.value = true
    }

    const handleEdit = (row) => {
      dialogType.value = 'edit'
      Object.keys(form).forEach(key => {
        form[key] = row[key]
      })
      dialogVisible.value = true
    }

    const handleDelete = (row) => {
      ElMessageBox.confirm(
        '确认删除该回访记录吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        customerApi.deleteVisit(row.id).then(() => {
          ElMessage.success('删除成功')
          fetchVisitRecords()
        }).catch(error => {
          console.error('删除回访记录失败:', error)
        })
      })
    }

    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        
        loading.value = true
        await customerApi.addVisit(form)
        
        ElMessage.success('回访记录保存成功')
        dialogVisible.value = false
        fetchVisitRecords()
      } catch (error) {
        console.error('表单验证失败:', error)
      } finally {
        loading.value = false
      }
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchVisitRecords()
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
      fetchVisitRecords()
    }

    const disabledDate = (time) => {
      return time.getTime() < Date.now() - 8.64e7 // 不能选择今天之前的日期
    }

    const canEdit = (visit) => {
      // 判断是否可以编辑回访记录，这里简单判断24小时内的记录可以编辑
      const visitTime = new Date(visit.visitTime).getTime()
      return Date.now() - visitTime <= 24 * 60 * 60 * 1000
    }

    const getCreditRatingType = (rating) => {
      const map = {
        'A': 'success',
        'B': 'warning',
        'C': 'info',
        'D': 'danger'
      }
      return map[rating]
    }

    const getCreditRatingText = (rating) => {
      const map = {
        'A': '优秀',
        'B': '良好',
        'C': '一般',
        'D': '较差'
      }
      return map[rating]
    }

    const getVisitType = (method) => {
      const map = {
        'phone': 'primary',
        'visit': 'success',
        'email': 'warning',
        'sms': 'info',
        'other': ''
      }
      return map[method]
    }

    const getVisitMethodText = (method) => {
      const map = {
        'phone': '电话',
        'visit': '上门',
        'email': '邮件',
        'sms': '短信',
        'other': '其他'
      }
      return map[method]
    }

    // 初始化数据
    onMounted(async () => {
      if (custId.value) {
        await fetchCustomerInfo()
        fetchVisitRecords()
      } else {
        ElMessage.error('客户ID不能为空')
        router.push('/customer/list')
      }
    })
    
    // 获取客户信息
    const fetchCustomerInfo = async () => {
      loading.value = true
      try {
        const res = await customerApi.getInfo(custId.value)
        customerInfo.value = res.data
      } catch (error) {
        console.error('获取客户信息失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 获取回访记录列表
    const fetchVisitRecords = () => {
      loading.value = true
      const params = {
        custId: custId.value,
        pageNum: currentPage.value,
        pageSize: pageSize.value
      }
      
      customerApi.getVisitList(params).then(res => {
        visitRecords.value = res.data.rows
        total.value = res.data.total
      }).catch(error => {
        console.error('获取回访记录失败:', error)
      }).finally(() => {
        loading.value = false
      })
    }

    return {
      customerInfo,
      visitRecords,
      currentPage,
      pageSize,
      total,
      dialogVisible,
      dialogType,
      formRef,
      form,
      loading,
      rules,
      goBack,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSubmit,
      handleCurrentChange,
      handleSizeChange,
      disabledDate,
      canEdit,
      getCreditRatingType,
      getCreditRatingText,
      getVisitType,
      getVisitMethodText,
      fetchVisitRecords
    }
  }
}
</script>

<style scoped>
.customer-visit {
  padding: 20px;
}

.page-header-content {
  font-size: 20px;
  font-weight: bold;
}

.visit-content {
  margin-top: 20px;
}

.info-card {
  margin-bottom: 20px;
}

.timeline-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #409EFF;
}

.visit-card {
  margin-bottom: 10px;
}

.visit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.visit-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.visit-method {
  min-width: 60px;
  text-align: center;
}

.visit-visitor {
  color: #666;
}

.visit-content {
  margin-top: 10px;
}

.visit-text {
  margin: 0;
  line-height: 1.6;
}

.visit-footer {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.next-visit-time {
  color: #666;
}

.empty-text {
  text-align: center;
  color: #909399;
  padding: 30px 0;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
}

:deep(.el-timeline-item__node--primary) {
  background-color: #409EFF;
}

:deep(.el-timeline-item__node--success) {
  background-color: #67C23A;
}

:deep(.el-timeline-item__node--warning) {
  background-color: #E6A23C;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style> 